<!-- pages/login/components/mobile.vue -->
<script setup>
	import { ref } from 'vue'
	import { getmobileCMSAPI,loginByCodeAPI } from '@/apis/user'
	import { useUserStore } from '@/stores'
	// 准备响应式数据
	const formData = ref({
		mobile:'',
		code:''
	})
	//是否勾选同意
	const isAgree = ref(false)
	const form = ref(null)
	//是否显示倒计时
	const showCountDown = ref(false)
	const countDownText = ref('获取验证码')
	// 倒计时到了触发的函数
	const onTimeup = () => {
		showCountDown.value = false
		countDownText.value = '再次获取验证码'
	}
	
	const onSendCMS = async() => {
		//对表单的输入框进行校验
		await form.value.validateField('mobile')
		const res = await getmobileCMSAPI({
			mobile:formData.value.mobile,	
			type:'login'
		})
		showCountDown.value = true
	}
	// 定义表单校验的规则
		const rules = {
			mobile: {
				rules: [
					{
						required: true,
						errorMessage: '请输入手机号码',
					},
					{ pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
				]
			},
			code: {
				rules: [
					{
						required: true,
						errorMessage: '请输入验证码',
					},
					{ pattern: /^\d{6}$/, errorMessage: '验证码格式不正确' }
				]
			}
		}
	//点击登录
	const onSubmit = async() => {
		if(isAgree.value === false){
			return uni.showToast({
				icon:'none',
				title:'请勾选我同意协议'
			})
		} 
		try{
			await form.value.validate()
			const { data } = await loginByCodeAPI(formData.value)
			console.log(data)
			const store = useUserStore()
			store.setUser(data)
			uni.showToast({
				title:'登录成功',
				icon:'success'
			})
			uni[store.openType]({
				url:store.redirectURL
			})
		}catch(e){
			console.log(e)
		}
		
	}
	//点击同意协议按钮
	const radioChange = () => {
		isAgree.value = !isAgree.value
	}
</script>

<template>
  <uni-forms class="login-form" ref="form" :model="formData" :rules="rules" >
    <uni-forms-item name="mobile">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入手机号"
        placeholder-style="color: #C3C3C5"
		v-model="formData.mobile"
      />
    </uni-forms-item>
    <uni-forms-item name="code">
      <uni-easyinput
        :input-border="false"
        :clearable="false"
        placeholder="请输入验证码"
        placeholder-style="color: #C3C3C5"
		v-model="formData.code"
      />
		<view class="text-button" v-if="showCountDown">
			<uni-countdown
				:second="10"
				:show-day="false"
				:show-minute="false"
				:show-hour="false"
				color="#16C2A3"
				@timeup="onTimeup"
			></uni-countdown>
			后发送验证码
		</view>
      <text class="text-button" @click="onSendCMS"  v-else>{{countDownText}}</text>
    </uni-forms-item>

    <view class="agreement">
      <radio :checked="isAgree" color="#16C2A3" @click="radioChange"/>
      我已同意
      <text class="link">用户协议</text>
      及
      <text class="link">隐私协议</text>
    </view>

    <button class="uni-button" @click="onSubmit">登 录</button>
  </uni-forms>
</template>

<script>
export default {
  options: {
    styleIsolation: 'shared'
  }
}
</script>

<style lang="scss">
@import './styles.scss';
</style>